import { useIntersectionObserver } from '@vueuse/core'
import defaltImg from '@/assets/images/200.png'
export default {
  // vue2 封装指令
  // install (Vue) {
  //   Vue.directive('指令名', {
  //     inserted (el, binding) {
  //       // 执行逻辑
  //     }
  //   })
  // }

  // vue3 指令
  install (app) {
    app.directive('imgLazy', {
      mounted (el, binding) {
        // el:img dom对象
        // console.log('el', el)
        // binding.value 指令绑定的值获取指令绑定的值
        // console.log('binding', binding)

        const { stop } = useIntersectionObserver(
          el,
          ([{ isIntersecting }], observerElement) => {
            // console.log(isIntersecting, observerElement)
            if (isIntersecting) {
              // console.log('错误', el.onerror)
              el.src = binding.value
              el.onerror = function fn () {
                el.src = defaltImg
              }
              // 当出现在可视区内 停止监听
              stop()
            }
          }
        )
      }
    })
  }
}
